package leetcode.code1392;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

//	执行用时：18 ms, 在所有 Java 提交中击败了23.30%的用户
//
//	内存消耗：42.2 MB, 在所有 Java 提交中击败了56.82%的用户
//
//	通过测试用例：76 / 76
	public String longestPrefix(String s) {
		char[] cs = s.toCharArray();
		int ans = 0;
		int basic = 31;//(int) 1e5 + 7;
		int mod = (int) 1e9 + 7;
		long h1 = 0, h2 = 0;
		long mul = 1;
		for (int i = 0; i < cs.length - 1; i++) {
			h1 = hash1(h1, basic, mod, cs[i]);
			h2 = hash2(h2, basic, mod, cs[cs.length - 1 - i], mul);
			mul = mul * basic % mod;
			if (h1 == h2) {
				ans = i + 1;
			}
		}
		return new String(cs, 0, ans);
	}

	private long hash2(long hash, int basic, int mod, int add, long mul) {
		return (hash + add * mul) % mod;
	}

	
//	执行用时：308 ms, 在所有 Java 提交中击败了5.11%的用户
//
//	内存消耗：41.7 MB, 在所有 Java 提交中击败了97.16%的用户
//
//	通过测试用例：76 / 76
//	private long pow(int basic, int n, int mod) {
//		if (n == 0)
//			return 1;
//		long b = pow(basic, n >> 1, mod) % mod;
//		long bb = b * b % mod;
//		return (n & 1) == 0 ? bb : bb * basic % mod;
//	}

	private long hash1(long hash, int basic, int mod, int add) {
		return (hash * basic + add) % mod;
	}

	@Override
	public void debug4() {
		H.compare("abababxx", this.longestPrefix("abababxxabababxx"));
		H.compare("abab", this.longestPrefix("ababab"));
		H.compare("l", this.longestPrefix("level"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		char[] cs = "Hello".toCharArray();
		System.out.println(new String(cs, 0, 0));
	}

}
